﻿
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameForKids
{
    class BilliardGame: GameScreen
    {
 
        private Texture2D background;
        //complete
        private SoundEffect timeTickSound;

        // dung cho loading
        public float timedelay = 4000f;
        public int timeold = 4;
        private bool playonetime = false;

        //help
        private string helpString="";
        protected HelpScreen helpScreen;

        // chart
        private ChartScreen chartScreen;

        // pause
        private PauseScreen pauseScreen;

        // win 
        private LevelCompleteScreen levelCompleteScreen;

        //cac button
        protected List<Button> buttons;
        protected Button chartButton;
        protected Button helpButton;
        protected Button musicButton;
        protected Button nextButton;
        protected Button backButton;
        protected Button calButton;
        protected Button playButton;

        // cac o chu
        private BilliardGamePlay gameplay;
        public static int level = 1;
        private SpriteFont numberFont;
        private SpriteFont helpFont;

        // nhac trong game
        private Song gameMusic;
        private SoundEffect buttonSound;
        private SoundEffect scrollSound;
        private Vector2 locationOfInfo;
        private string textInfo="";
        private TouchCollection touches;
        private SoundEffect buttonPressSound;
        private SoundEffect popupSound;

        protected Boolean danload = false;
        protected Boolean vaogame = false;

        private enum ViewState
        {
            None,
            Loading,
            Playing,
            HelpScreen,
            ChartScreen,
            Pause,
            OnComplete
        }
        ViewState viewState;

        public BilliardGame()
        {
            TransitionOnTime = TimeSpan.FromSeconds(0);
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load Content.
        /// </summary>
        public override void Initialize()
        {
            viewState = ViewState.None;
        }

        public override void Activate(bool instancePreserved)
        {
            // Huy Phan INIT
            Suport.Content = ScreenManager.Game.Content;
            Suport.Textures.Clear();
            Suport.SoundEffects.Clear();


            level = 1;
            locationOfInfo = Vector2.Zero;
            numberFont = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/NumberFont");
            helpFont = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/HelpFont");
            buttonPressSound = ScreenManager.Game.Content.Load<SoundEffect>("Login/Sounds/button_click");
            popupSound = ScreenManager.Game.Content.Load<SoundEffect>("Login/Sounds/login_in");
           
            // khoi tao cac button trong game
            buttons = new List<Button>();

            chartButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_chart"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_chart_press"),
              ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_chart_press"));
            chartButton.Location = new Point(10, 50);
            chartButton.Clicked += new EventHandler(chartButton_Clicked);

            helpButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_help"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_help_press"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_help_press"));
            helpButton.Location = new Point(10, 150);
            helpButton.Clicked += new EventHandler(helpButton_Clicked);

            musicButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/music_on"),
                ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/music_off"),
                ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/music_off"));
            musicButton.Location = new Point(726, 50);
            musicButton.Clicked += new EventHandler(musicButton_Clicked);
            if (!GameForKids.ISMUSIC)
                musicButton.Hold = true;


            backButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_pre"),
               ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_pre_press"),
               ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_pre_press"));
            backButton.Location = new Point(10, 400);
            backButton.Clicked += new EventHandler(backButton_Clicked);
            backButton.Disable();

            nextButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_next"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_next_press"),
              ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_next_press"));
            nextButton.Location = new Point(720, 400);
            nextButton.Clicked += new EventHandler(nextButton_Clicked);

            playButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("Pause/resumeButton"),
           ScreenManager.Game.Content.Load<Texture2D>("Pause/resumeButtonPress"),
           ScreenManager.Game.Content.Load<Texture2D>("Pause/resumeButtonPress"));
            playButton.Location = new Point((GameForKids.WIDTH - playButton.width) / 2, (GameForKids.HEIGHT - playButton.height) / 2);
            playButton.Clicked += playButton_Clicked;

            calButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_cal"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_cal_press"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_cal_press"));
            calButton.Location = new Point(726, 150);
            calButton.Clicked += calButton_Clicked;

            buttons.Add(chartButton);
            buttons.Add(helpButton);
            buttons.Add(musicButton);
            buttons.Add(backButton);
            buttons.Add(nextButton);
            buttons.Add(calButton);
            // on complete show

            chartScreen = new ChartScreen(ScreenManager.Game);
            chartScreen.Clicked += new EventHandler(chartScreen_Clicked);

            gameMusic = ScreenManager.Game.Content.Load<Song>("BilliardGame/Sounds/music");
            buttonSound = ScreenManager.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/buttonPress");
            scrollSound = ScreenManager.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/sliding");
            timeTickSound = ScreenManager.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/timetick");
           
            background = ScreenManager.Game.Content.Load<Texture2D>("BilliardGame/Images/background");

            if (GameForKids.language == GameForKids.VIET)
            {
                helpString = "CÁCH CHƠI :\n" +
                    "Trò chơi này giống với trò bi da 3 bi\n" +
                    "nhưng nhiệm vụ của bạn là dùng bi trắng\n" +
                    "để đưa tất cả các bi vào lỗ.\n" +
                    "khi hoàn thành mỗi màn chơi điểm số sẽ được lưu\n" +
                    "                     lại, bạn có thể mở đồ thị để xem bảng\n" +
                    "                     điểm được thống kê theo màn. Điểm số\n" +
                    "                     được tính theo công thức mặc định, bạn\n" +
                    "                     có thể vào setting để đặt lại công thức !";
            }
            else
            {
                helpString = "GUIDE :\n" +
                   "This game like billiard game. Your task is control \n" +
                   "the white ball to put another ball into the hole\n" +
                   "There have 4 level and increasing difficulty,\n" +
                   "when completion of each level, the score will\n" +
                   "                     be saved. You can open to see the graph\n" +
                   "                     score of each level .Score is calculated by\n" +
                   "                     default formula. You can set the formula\n" +
                   "                     by select the calculator icon !";
            }
            helpScreen = new HelpScreen(ScreenManager.Game, helpString);
            helpScreen.Clicked += new EventHandler(helpScreen_Clicked);

            pauseScreen = new PauseScreen(ScreenManager.Game);
            levelCompleteScreen = new LevelCompleteScreen(ScreenManager.Game);


            if (GameForKids.ISMUSIC)
            {
                MediaPlayer.Play(gameMusic);
                MediaPlayer.IsRepeating = true;
            }
            gameplay = new BilliardGamePlay(ScreenManager.Game);
            gameplay.startNewLevel(level);
            base.Activate(instancePreserved);
        }

        void calButton_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
                buttonPressSound.Play();
            if (vaogame)
            {
                pauseScreen.showPause();
                viewState = ViewState.Pause;
            }
            ScreenManager.AddScreen(new CalculatorScreen(), null);
        }

        void playButton_Clicked(object sender, EventArgs e)
        {
            viewState = ViewState.Loading;
            danload = true;
            vaogame = true;
        }

        void chartScreen_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
            chartScreen.HideChart();
            if (vaogame)
            {
                if (danload)
                    viewState = ViewState.Loading;
                else
                    viewState = ViewState.Playing;
            }
            else
                viewState = ViewState.None;
        }

        void helpScreen_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
            helpScreen.hidehelp();
            if (vaogame)
            {
                if (danload)
                    viewState = ViewState.Loading;
                else
                    viewState = ViewState.Playing;
            }
            else
                viewState = ViewState.None;
        }

        private void nextlevel()
        {
            if (level == 4)
            {
                level = 1;
                gameplay.startNewLevel(level);
                backButton.Disable();
                nextButton.Enable();
            }
            else if (level < 4)
            {
                level++;
                gameplay.startNewLevel(level);
                if (level == 4)
                nextButton.Disable();
                backButton.Enable();
            }
        }

        void nextButton_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
                buttonSound.Play();

            viewState = ViewState.Loading;
            timedelay = 4000f;
            danload = true;
            nextlevel();
        }
        private void backlevel()
        {
            if (level > 1)
            {
                level--;
                gameplay.startNewLevel(level);
            }
            if (level == 1)
                backButton.Disable();
            nextButton.Enable();
        }

        void backButton_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
                buttonSound.Play();
            timedelay = 4000f;
            viewState = ViewState.Loading;
            danload = true;
            backlevel();
        }

        void musicButton_Clicked(object sender, EventArgs e)
        {
            if (musicButton.Hold == false)
            {
                musicButton.Hold = true;
                GameForKids.ISMUSIC = false;
                MediaPlayer.Stop();
            }
            else
            {
                musicButton.Hold = false;
                GameForKids.ISMUSIC = true;
                MediaPlayer.Play(gameMusic);
                MediaPlayer.IsRepeating = true;
            }
        }

        void helpButton_Clicked(object sender, EventArgs e)
        {
            if (viewState != ViewState.HelpScreen)
            {
                helpScreen.showhelp();
                viewState = ViewState.HelpScreen;

            }
            else
            {
                helpScreen.hidehelp();
                if (vaogame)
                {
                    if (danload)
                        viewState = ViewState.Loading;
                    else
                        viewState = ViewState.Playing;

                }
                else
                    viewState = ViewState.None;
            }
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
        }

        void chartButton_Clicked(object sender, EventArgs e)
        {
            if (viewState == ViewState.HelpScreen)
                helpScreen.hidehelp();
            chartScreen.ShowChart();
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
            viewState = ViewState.ChartScreen;
        }


        public void loading(float elapsed)
        {
            timedelay = timedelay - elapsed;
            if (timeold != ((int)timedelay / 1000) && timedelay > 0)
            {
                timeold = (int)timedelay / 1000;
                playonetime = true;
            }
            if (playonetime && GameForKids.ISMUSIC)
            {
                timeTickSound.Play();
                playonetime = false;
            }

            if (timedelay <= 0)
            {
                viewState = ViewState.Playing;
                danload = false;
                timedelay = 4000f;
            }
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            if (timedelay >= 0f && viewState == ViewState.Loading)
            {
                loading(elapsed);
            }

            if (gameplay.checkComplete())
            {
                if (viewState != ViewState.OnComplete)
                {
                    int _diem = gameplay.getScore();
                    levelCompleteScreen.diem = _diem;
                    levelCompleteScreen.showScreen();
                    viewState = ViewState.OnComplete;
                    gameplay.saveScore(_diem);
                }
                levelCompleteScreen.Update(gameTime);
            }

            // bat su kien phim khi pause
            if (PauseClickState.clickstate == PauseClickState.ClickState.menu)
            {
                PauseClickState.clickstate = PauseClickState.ClickState.none;
                GoMenu();
            }
            else if (PauseClickState.clickstate == PauseClickState.ClickState.resume)
            {
                PauseClickState.clickstate = PauseClickState.ClickState.none;
                Resume();
            }
            else if (PauseClickState.clickstate == PauseClickState.ClickState.replay)
            {
                PauseClickState.clickstate = PauseClickState.ClickState.none;
                Replay();
            }
            // bat su kien phim khi win
            if (LevelCompleteClickState.clickstate == LevelCompleteClickState.ClickState.menu)
            {
                LevelCompleteClickState.clickstate = LevelCompleteClickState.ClickState.none;
                GoMenu();
            }
            else if (LevelCompleteClickState.clickstate == LevelCompleteClickState.ClickState.replay)
            {
                LevelCompleteClickState.clickstate = LevelCompleteClickState.ClickState.none;
                Replay();
            }
            else if (LevelCompleteClickState.clickstate == LevelCompleteClickState.ClickState.next)
            {
                LevelCompleteClickState.clickstate = LevelCompleteClickState.ClickState.none;
                Next();
            }

            if (viewState == ViewState.Playing)
                gameplay.Update(gameTime); 
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spritebatch = ScreenManager.SpriteBatch;
            spritebatch.Begin();
            spritebatch.Draw(background, new Vector2(0, 0), Color.White);

            if (viewState != ViewState.None && viewState != ViewState.Loading && vaogame && !danload)
            {
                gameplay.Draw(gameTime, spritebatch);
            }
            foreach (Button button in buttons)
            {
                button.Draw(spritebatch);
            }
            if (viewState == ViewState.None)
            {
                playButton.Draw(spritebatch);
            }
            textInfo = "";
            if (GameForKids.language == GameForKids.ANH)
            {
                textInfo += "Billiard   --   " + "Level: " + level.ToString() + "   --   " + "Name: " + GameForKids.userName;
            }
            else
            {
                textInfo += "Billiard   --   " + "Màn: " + level.ToString() + "   --   " + "Tên: " + GameForKids.userName;
            }
            locationOfInfo.X = (GameForKids.WIDTH - helpFont.MeasureString(textInfo).X) / 2;
            locationOfInfo.Y = 445;
            if (vaogame)
                spritebatch.DrawString(helpFont,
                    textInfo,
                    locationOfInfo,
                    Color.White);

            helpScreen.Draw(spritebatch);
            chartScreen.Draw(spritebatch);
            pauseScreen.Draw(spritebatch);
            levelCompleteScreen.Draw(spritebatch);

            if (viewState == ViewState.Loading && timedelay < 4000)
                spritebatch.DrawString(numberFont,
                                        ((int)timedelay / 1000).ToString(),
                                        new Vector2((GameForKids.WIDTH - numberFont.MeasureString("4").X) / 2,
                                                    (GameForKids.HEIGHT - numberFont.MeasureString("4").Y) / 2),
                                        Color.Orange,
                                        0f,
                                        Vector2.Zero,
                                        1.0f,
                                        SpriteEffects.None,           
                                        0);
            /*
            var appCurrentMemoryUsage = DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
            var appPeakMemoryUsage = DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
            spritebatch.DrawString(numberFont, "Current RAM: " + appCurrentMemoryUsage.ToString(), new Vector2(10, 10), Color.White);
            spritebatch.DrawString(numberFont, "Total RAM: " + appPeakMemoryUsage, new Vector2(10, 30), Color.White);
            */
            spritebatch.End();
        }

        public void Next()
        {
            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (levelCompleteScreen.show)
                levelCompleteScreen.hideScreen();
            viewState = ViewState.Loading;
            nextlevel();
        }

        public void Resume()
        {

            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (pauseScreen.show)
                pauseScreen.hidePause();
            if (danload)
                viewState = ViewState.Loading;
            else
                viewState = ViewState.Playing;
        }

        public void Replay()
        {

            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (pauseScreen.show)
                pauseScreen.hidePause();

            viewState = ViewState.Loading;
            danload = true;

            if (levelCompleteScreen.show)
                levelCompleteScreen.hideScreen();
            gameplay.startNewLevel(level);
        }

        public void GoMenu()
        {
            if (GameForKids.ISMUSIC)
                MediaPlayer.Stop();
            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (pauseScreen.show)
                pauseScreen.hidePause();

            viewState = ViewState.None;
            danload = false;

            if (levelCompleteScreen.show)
                levelCompleteScreen.hideScreen();
            GameForKids.gameState = GameState.MainMenu;
            ExitScreen();
            if (GameForKids.ISMUSIC)
            {
                gameMusic = ScreenManager.Game.Content.Load<Song>("MainMenu/Sounds/music_of_main_menu");
                MediaPlayer.IsRepeating = true;
                MediaPlayer.Play(gameMusic);
            }
            MainMenuScreen.viewState = VIEWSTATE.effectIN;
        }


        public override void HandleInput(Microsoft.Xna.Framework.GameTime gameTime, InputState input)
        {
            PlayerIndex player;
            if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player) && viewState != ViewState.OnComplete)
            {
                if (!vaogame)
                {
                    if (viewState == ViewState.ChartScreen)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            scrollSound.Play();
                        }
                        chartScreen.HideChart();
                        viewState = ViewState.None;
                    }
                    else if (viewState == ViewState.HelpScreen)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            scrollSound.Play();
                        }
                        helpScreen.hidehelp();
                        viewState = ViewState.None;
                    }
                    else
                    {
                        viewState = ViewState.None;
                        GameForKids.gameState = GameState.MainMenu;
                        ExitScreen();
                        if (GameForKids.ISMUSIC)
                        {
                            gameMusic = ScreenManager.Game.Content.Load<Song>("MainMenu/Sounds/music_of_main_menu");
                            MediaPlayer.IsRepeating = true;
                            MediaPlayer.Play(gameMusic);
                        }
                        MainMenuScreen.viewState = VIEWSTATE.effectIN;
                    }
                }
                else if (viewState != ViewState.Pause)
                {
                    if (viewState == ViewState.ChartScreen)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            scrollSound.Play();
                        }
                        chartScreen.HideChart();
                        if (danload)
                            viewState = ViewState.Loading;
                        else
                            viewState = ViewState.Playing;
                    }
                    else if (viewState == ViewState.HelpScreen)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            scrollSound.Play();
                        }
                        helpScreen.hidehelp();
                        if (danload)
                            viewState = ViewState.Loading;
                        else
                            viewState = ViewState.Playing;
                    }
                    else
                    {
                        if (GameForKids.ISMUSIC)
                            popupSound.Play();
                        pauseScreen.showPause();
                        viewState = ViewState.Pause;
                    }
                }
                else if (viewState == ViewState.Pause)
                {
                    pauseScreen.hidePause();
                    if (helpScreen.show)
                        helpScreen.hidehelp();
                    if (chartScreen.show)
                        chartScreen.HideChart();
                    if (danload)
                        viewState = ViewState.Loading;
                    else
                        viewState = ViewState.Playing;
                }
            }
            touches = input.TouchState;
            if(touches.Count > 0)
            {
                TouchLocation touch = touches[0];
                switch (viewState)
                {
                    case ViewState.None:
                        {
                            helpButton.TouchEvent(touch);
                            chartButton.TouchEvent(touch);
                            musicButton.TouchEvent(touch);
                            calButton.TouchEvent(touch);
                            playButton.TouchEvent(touch);
                        }; break;
                    case ViewState.Loading:
                        {
                            foreach (Button button in buttons)
                            {
                                button.TouchEvent(touch);
                            }
                        }; break;
                    case ViewState.Playing:
                        gameplay.TouchEvent(touch);
                        foreach (Button button in buttons)
                        {                     
                            button.TouchEvent(touch);
                        }
                        break;
                    case ViewState.Pause:
                        {
                            pauseScreen.TouchEvent(touch);
                        }; break;
                    case ViewState.HelpScreen:
                          {
                            helpScreen.TouchEvent(touch);
                            helpButton.TouchEvent(touch);
                            chartButton.TouchEvent(touch);
                            musicButton.TouchEvent(touch);
                            calButton.TouchEvent(touch);
                        }
                        break;
                    case ViewState.ChartScreen:
                         {
                            chartScreen.TouchEvent(touch);
                            musicButton.TouchEvent(touch);
                            calButton.TouchEvent(touch);
                        };
                        break;

                    case ViewState.OnComplete:
                        {
                          levelCompleteScreen.TouchEvent(touch);      
                        };break;
                }
            }
        }
    }
}
